/* Program name: lastcurrent_dates.sas*/
/* Objective: create a variable clled currdate that is the date that a deqlineunt balance was last not delinquent (current)*/
/* This code requires the mopdate variable createdd in clean_tradeline01.sas, so it should be run after those programs*/

OPTIONS LINESIZE=79;

libname local './';
libname out './';
%include "/data/tu_formats.sas";

%macro makedates(sufx);
data out.cleantrade&sufx.;
     set out.interestrate&sufx.;
     format mopdate datecurr datefirst120 yymmn6.;

     * find the first time the account was last recent;
     if mop ge 2 then do;
	   if dtclose gt 0 then mopdate = input(put(dtclose,6.),yymmn6.);
	   if dtclose le 0 and dtpdout gt 0 then mopdate = input(put(dtpdout,6.),yymmn6.);
	   if dtclose le 0 and dtpdout le 0 then mopdate = input(put(dtveri,6.),yymmn6.);
	   statuscurr=mop;
	   monthscurr=0;
	   do until (statuscurr=1 or monthscurr=49);
	      monthscurr=monthscurr+1;
	      if substr(paypat,monthscurr,1) eq 'X' then continue;
	      statuscurr=input(substr(paypat,monthscurr,1),best12.);
	      end;
     end;

     *find the first time account was 120+dpd;
     if mop = 5 then do;
	   if dtclose gt 0 then mopdate = input(put(dtclose,6.),yymmn6.);
	   if dtclose le 0 and dtpdout gt 0 then mopdate = input(put(dtpdout,6.),yymmn6.);
	   if dtclose le 0 and dtpdout le 0 then mopdate = input(put(dtveri,6.),yymmn6.);
	   statusf120=mop;
	   monthsf120=0;
	   do until (statusf120 ^= 5 or monthsf120=49);
	      monthsf120=monthsf120+1;
	      if substr(paypat,monthsf120,1) eq 'X' then continue;
	      statusf120=input(substr(paypat,monthsf120,1),best12.);
	      end;
     end;

     * create the dates;	
     if statuscurr=. then monthscurr=.;
     if statusf120=. then monthsf120=.;
     datecurr =  intnx('month',mopdate,-monthscurr);
     datefirst120 =  intnx('month',mopdate,-monthsf120);
     run;
*To look at things to make sure they are working correctly;
*proc print data= out.cleantrade99 (obs=10);
*     var teditseq paypat mop mopdate monthscurr datecurr monthsf120 datefirst120;
*     where not missing(datecurr) or not missing(datefirst120);
*     run;
%mend;

%makedates(201006);
%makedates(201206);
%makedates(201406);
endsas;
